package com.siebre.picclife.asynctask.springcontext;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.siebre.picclife.asynctask.service.TaskManager;
import com.siebre.picclife.asynctask.service.TaskRecoverer;

/**
 * Bootstrap task processing. Make sure the recovery is executed before 
 * starting task processing.
 * 
 * @author ZhangChi
 * @since 2015年4月10日
 *
 */
public class TaskProcessingBootstrap implements ApplicationListener<ContextRefreshedEvent> {
	
	private final TaskManager manager;
	
	private final TaskRecoverer recoverer;
	
	private final boolean auto;

	public TaskProcessingBootstrap(TaskManager manager, TaskRecoverer recoverer) {
		this.manager = manager;
		this.recoverer = recoverer;
		auto = true;
	}

	/**
	 * 
	 * @param manager
	 * @param recoverer
	 * @param auto true indicates that the bootstrap is triggered by context refresh event.
	 */
	public TaskProcessingBootstrap(TaskManager manager, TaskRecoverer recoverer, boolean auto) {
		this.manager = manager;
		this.recoverer = recoverer;
		this.auto = auto;
	}

	public void bootstrap() {
		recoverer.recover();
		manager.start();
	}

	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (auto) {
			bootstrap();
		}
	}
}
